import { Injectable, Logger } from '@nestjs/common';
import { isAddress } from 'ethers';
import { UserListResponse, UserDetailResponse } from './response/user-response';
import { TbUser } from '../entities/TbUser';
import { UserModel } from '../models/user-model';
import { SaveUserDto } from './dto/user.dto';

@Injectable()
export class UserService {
  private readonly logger = new Logger(UserService.name); // 实例化日志

  constructor(private readonly userModel: UserModel) {}

  async getUserList(
    address: string,
    age: number,
    limit: number,
    offset: number,
  ): Promise<[UserListResponse, number]> {
    const [tmpList, count] = await this.userModel.getUserList(
      address,
      age,
      limit,
      offset,
    );
    const list = new UserListResponse(tmpList);
    return [list, count];
  }

  async getUserDetail(id: number): Promise<UserDetailResponse> {
    const detail = await this.userModel.getUserById(id);
    return new UserDetailResponse(detail);
  }

  async saveUser(data: SaveUserDto): Promise<TbUser> {
    if (!isAddress(data.address)) {
      throw new Error('Invalid user address'); // 自定义错误
    }

    this.logger.log('保存用户日志', data);

    const model = new TbUser();
    if (data.id > 0) {
      model.id = data.id;
    }
    model.address = data.address;
    model.realName = data.real_name;
    model.nickName = data.nick_name;
    model.age = data.age;

    return this.userModel.saveUser(model);
  }

  async delUser(id: number, address: string): Promise<void> {
    await this.userModel.delUser(id, address);
  }
}
